package com.zpz.framework.zpzoauth.config.oauth.authorization.exouath.authenticator;

import com.alibaba.fastjson.JSON;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthCommonConstant;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultMsg;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultStatus;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthRequestUtil;
import com.zpz.framework.zpzoauth.dao.FrameDepartmentMapper;
import com.zpz.framework.zpzoauth.pojo.pe.GetDepartmentStatusPe;
import com.zpz.framework.zpzoauth.pojo.po.OauthClientDetails;
import com.zpz.framework.zpzoauth.pojo.qo.ModifyUserLoginDateQo;
import com.zpz.framework.zpzoauth.pojo.vo.UserAuthenticationVo;
import com.zpz.framework.zpzoauth.config.oauth.authorization.exouath.ZpzOauthIntegrationAuthentication;
import com.zpz.framework.zpzoauth.service.ZpzOauthFrameUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
@Component
@Primary
public class ZpzOauthUsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ZpzOauthFrameUserService iFrameUserService  ;
    @Resource
    private FrameDepartmentMapper frameDepartmentMapper;
    @Autowired
    private ZpzOauthRequestUtil zpzOauthRequestUtil;
    private final static String U_P_AUTH_TYPE = "password";
    @Override
    public UserAuthenticationVo authenticate(ZpzOauthIntegrationAuthentication integrationAuthentication) {
        log.info("密码模式登录：入参："+ JSON.toJSONString(integrationAuthentication));
        ZpzOauthResultMsg<UserAuthenticationVo> resultMsg = iFrameUserService.getUserInfoByUserName(integrationAuthentication.getUsername(),integrationAuthentication.getClientId());
        log.info("密码模式登录：查询用户结果："+ JSON.toJSONString(resultMsg));
        integrationAuthentication.setAuthParameters(integrationAuthentication.getAuthParameters());
        if (resultMsg!=null&&resultMsg.getData()!=null&&resultMsg.getCode()==0){
            UserAuthenticationVo data = resultMsg.getData();
            OauthClientDetails client = zpzOauthRequestUtil.getClient(integrationAuthentication.getClientId());
            if (client.getAccessType()==2){
                // 基于部门的权限划分 部门禁用或者冻结旗下用户同样不能登录
                List<GetDepartmentStatusPe> getDepartmentStatusPes = frameDepartmentMapper.selectDepartmentStatus(data.getUserCode());
                for (GetDepartmentStatusPe gdsp:getDepartmentStatusPes) {
                    if (gdsp.getStatus()!=0){
                        data.setStatus(-1);
                        throw new OAuth2Exception("登录授权失败[ZPZ_DEFINED_OAUTH2_EXCEPTION]["+ ZpzOauthResultStatus.OAUTH_10009.getCode() +"]："+ZpzOauthResultStatus.OAUTH_10009.getMessage()+"：：："+resultMsg.getMessage());
                    }
                }
            }
            data.setUserName(integrationAuthentication.getUsername());
            if (!resultMsg.getData().getType().contains(integrationAuthentication.getClientId())){
                throw new OAuth2Exception("登录授权失败[ZPZ_DEFINED_OAUTH2_EXCEPTION]["+ ZpzOauthResultStatus.OAUTH_10008.getCode() +"]："+ ZpzOauthResultStatus.OAUTH_10008.getMessage()+"：：："+resultMsg.getMessage());
            }
            if (resultMsg.getData().getStatus()!= ZpzOauthCommonConstant.USER_STATUS_ENABLED){
                throw new OAuth2Exception("登录授权失败[ZPZ_DEFINED_OAUTH2_EXCEPTION]["+ ZpzOauthResultStatus.OAUTH_10009.getCode() +"]："+ ZpzOauthResultStatus.OAUTH_10009.getMessage()+"：：："+resultMsg.getMessage());
            }
            if (StringUtils.isNotBlank(data.getLockType())&&data.getLockType().contains(integrationAuthentication.getClientId())){
                throw new OAuth2Exception("登录授权失败[ZPZ_DEFINED_OAUTH2_EXCEPTION]["+ ZpzOauthResultStatus.OAUTH_10010.getCode() +"]："+ ZpzOauthResultStatus.OAUTH_10010.getMessage()+"：：："+resultMsg.getMessage());
            }
            ModifyUserLoginDateQo t=new ModifyUserLoginDateQo();
            t.setUserCode(data.getUserCode());
            t.setClientId(integrationAuthentication.getClientId());
            t.setLoginDate(new Date());
            ZpzOauthResultMsg<Boolean> flag = iFrameUserService.modifyUserLoginDate(t);
            log.info("::::::::::修改最新登录时间： "+JSON.toJSONString(flag));
            return data;
        }else{
            throw new OAuth2Exception("登录授权失败[ZPZ_DEFINED_OAUTH2_EXCEPTION]["+ ZpzOauthResultStatus.OAUTH_10005.getCode() +"]："+ ZpzOauthResultStatus.OAUTH_10005.getMessage()+"：：："+resultMsg.getMessage());
        }
    }

    @Override
    public void prepare(ZpzOauthIntegrationAuthentication integrationAuthentication) {

    }

    @Override
    public boolean support(ZpzOauthIntegrationAuthentication integrationAuthentication) {
    	//增加空判断，支持授权码模式
        return StringUtils.isEmpty(integrationAuthentication.getAuthType())
        		||U_P_AUTH_TYPE.equals(integrationAuthentication.getAuthType());
    }
}
